'use strict';

const Controller = require('egg').Controller;

class EmailController extends Controller {
    async sendMail() {
        const { service } = this.ctx;
        const email = this.ctx.request.body.email;  // 接收者的邮箱
        let emailReg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,4}$/;
        if (!emailReg.test(email)) throw { code: '02', msg: '请输入正确邮箱' }

        const subject = '阅文说注册验证码';
        const yzCode = Math.random().toString().slice(-6);
        const text = `验证码为${yzCode},30分钟内有效`;
        const result = await service.email.sendMail(email, subject, text);

        if (!result) throw { code: '02', msg: '验证码发送失败' }

        service.redis.set(email, yzCode, 1800);
        this.ctx.body = {
            code: '00',
            msg: '验证码发送成功'
        }
    }

}

module.exports = EmailController;
